<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑环境' : '新建环境'"
    width="700px"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="环境名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入环境名称，如：开发环境" />
      </el-form-item>

      <el-form-item label="基础URL" prop="base_url">
        <el-input v-model="formData.base_url" placeholder="请输入基础URL，如：https://api.example.com" />
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入环境描述"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否默认">
            <el-switch v-model="formData.is_default" />
            <div class="form-tip">设为默认环境后，其他环境的默认状态将被取消</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否激活">
            <el-switch v-model="formData.is_active" />
            <div class="form-tip">只有激活的环境才能被使用</div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 环境变量 -->
      <el-form-item label="环境变量">
        <div class="key-value-editor">
          <div class="editor-header">
            <span class="editor-title">配置环境级别的变量，可在接口参数中引用</span>
          </div>
          <div
            v-for="(variable, index) in variableList"
            :key="index"
            class="key-value-row"
          >
            <el-input
              v-model="variable.key"
              placeholder="变量名，如：API_VERSION"
              style="width: 40%"
            />
            <el-input
              v-model="variable.value"
              placeholder="变量值，如：v1"
              style="width: 40%; margin-left: 10px"
            />
            <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              @click="removeVariable(index)"
            >
              删除
            </el-button>
          </div>
          <el-button size="small" @click="addVariable">
            <el-icon><Plus /></el-icon>
            添加变量
          </el-button>
        </div>
      </el-form-item>

      <!-- 全局请求头 -->
      <el-form-item label="全局请求头">
        <div class="key-value-editor">
          <div class="editor-header">
            <span class="editor-title">配置所有接口都会携带的请求头</span>
          </div>
          <div
            v-for="(header, index) in headerList"
            :key="index"
            class="key-value-row"
          >
            <el-input
              v-model="header.key"
              placeholder="Header名称，如：Authorization"
              style="width: 40%"
            />
            <el-input
              v-model="header.value"
              placeholder="Header值，如：Bearer {{token}}"
              style="width: 40%; margin-left: 10px"
            />
            <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              @click="removeHeader(index)"
            >
              删除
            </el-button>
          </div>
          <el-button size="small" @click="addHeader">
            <el-icon><Plus /></el-icon>
            添加请求头
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 变量引用说明 -->
    <el-alert
      title="变量引用说明"
      type="info"
      :closable="false"
      style="margin-bottom: 20px"
    >
      <div class="variable-help">
        <p><strong>在接口参数中引用变量的方式：</strong></p>
        <ul>
          <li><code>{{variable_name}}</code> - 引用环境变量</li>
          <li><code>{{API_VERSION}}</code> - 引用API版本变量</li>
          <li><code>https://api.example.com/{{API_VERSION}}/users</code> - 在URL中使用</li>
        </ul>
        <p><strong>变量优先级：</strong>场景变量 > 环境变量 > 接口默认值</p>
      </div>
    </el-alert>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useToast } from 'vue-toastification'
import { apiAutomationApi } from '@/api/apiAutomation'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  environmentData: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'confirm'])

const toast = useToast()
const formRef = ref()

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  base_url: '',
  variables: {},
  headers: {},
  is_default: false,
  is_active: true
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入环境名称', trigger: 'blur' },
    { max: 100, message: '环境名称不能超过100个字符', trigger: 'blur' }
  ],
  base_url: [
    { 
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的URL，如：https://api.example.com',
      trigger: 'blur'
    },
    { max: 500, message: 'URL不能超过500个字符', trigger: 'blur' }
  ]
}

// 键值对编辑器数据
const variableList = ref([])
const headerList = ref([])

// 提交状态
const submitLoading = ref(false)

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.environmentData) {
    Object.assign(formData, {
      ...props.environmentData,
      variables: props.environmentData.variables || {},
      headers: props.environmentData.headers || {}
    })
  } else {
    // 重置表单
    Object.assign(formData, {
      name: '',
      description: '',
      base_url: '',
      variables: {},
      headers: {},
      is_default: false,
      is_active: true
    })
  }

  // 初始化键值对编辑器
  initKeyValueEditors()
}

// 初始化键值对编辑器
const initKeyValueEditors = () => {
  // 环境变量
  variableList.value = Object.entries(formData.variables || {}).map(([key, value]) => ({ key, value }))
  if (variableList.value.length === 0) {
    variableList.value.push({ key: '', value: '' })
  }

  // 全局请求头
  headerList.value = Object.entries(formData.headers || {}).map(([key, value]) => ({ key, value }))
  if (headerList.value.length === 0) {
    headerList.value.push({ key: '', value: '' })
  }
}

// 环境变量操作
const addVariable = () => {
  variableList.value.push({ key: '', value: '' })
}

const removeVariable = (index) => {
  variableList.value.splice(index, 1)
  if (variableList.value.length === 0) {
    variableList.value.push({ key: '', value: '' })
  }
}

// 请求头操作
const addHeader = () => {
  headerList.value.push({ key: '', value: '' })
}

const removeHeader = (index) => {
  headerList.value.splice(index, 1)
  if (headerList.value.length === 0) {
    headerList.value.push({ key: '', value: '' })
  }
}

// 处理表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true

    // 处理环境变量
    const variables = {}
    variableList.value.forEach(item => {
      if (item.key && item.value) {
        variables[item.key] = item.value
      }
    })

    // 处理全局请求头
    const headers = {}
    headerList.value.forEach(item => {
      if (item.key && item.value) {
        headers[item.key] = item.value
      }
    })

    const submitData = {
      ...formData,
      variables,
      headers
    }

    if (props.isEdit) {
      await apiAutomationApi.updateEnvironment(props.environmentData.id, submitData)
      toast.success('环境更新成功')
    } else {
      await apiAutomationApi.createEnvironment(submitData)
      toast.success('环境创建成功')
    }

    emit('confirm')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
.key-value-editor {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background-color: #fafafa;

  .editor-header {
    margin-bottom: 12px;

    .editor-title {
      color: #606266;
      font-size: 13px;
    }
  }

  .key-value-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.variable-help {
  ul {
    margin: 8px 0;
    padding-left: 20px;
  }

  li {
    margin-bottom: 4px;
  }

  code {
    background-color: #f5f5f5;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    color: #e6a23c;
  }

  p {
    margin: 8px 0;
  }
}

.dialog-footer {
  text-align: right;
}
</style>